﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Youz.Common.BLL;
using Youz.Common.Entity;
using Youz.Common.Helper;
using Youz.CreditRepay.BLL;
using Youz.CreditRepay.Entity;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Web.SessionState;
using System.Threading.Tasks;
using Youz.CreditRepay.BLL.Pay;

namespace Youz.CreditRepay.Server
{
    /// <summary>
    /// App 的摘要说明
    /// </summary>
    public class App : IHttpHandler, IRequiresSessionState
    {
        Member_InfoBLL bllMemberInfo = new Member_InfoBLL();
        Member_AccountBLL bllMemberAccount = new Member_AccountBLL();
        Member_CertifiedBLL bllMemberCertified = new Member_CertifiedBLL();
        CR_BankCardBLL bllBankCard = new CR_BankCardBLL();
        Member_WithdrawBLL bllWithdraw = new Member_WithdrawBLL();
        CR_RepaymentPlanBLL bllRepaymentPlan = new CR_RepaymentPlanBLL();
        CR_RepaymentPlanItemBLL bllRepaymentPlanItem = new CR_RepaymentPlanItemBLL();        

        string memberAccount;

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            if (context.Request.RequestType.ToUpper() == "OPTIONS")
            {
                context.Response.Write(string.Empty);
                context.Response.End();
                return;
            }

            string _type = WebHelper.Get("type");
            string result = string.Empty;

            memberAccount = WebHelper.Post("MemberAccount");

            switch (_type)
            {
                case "Login":
                    result = Login();
                    break;
                case "Logout":
                    result = Logout();//登录
                    break;
                case "GetVersion":
                    result = GetVersion();
                    break;
                case "SetNickname":
                    result = SetNickname();
                    break;
                case "ChangeLoginPassword":
                    result = ChangeLoginPassword();
                    break;
                case "ChangePayPassword":
                    result = ChangePayPassword();
                    break;
                case "Authentication":
                    result = AuthenticationMember();
                    break;
                case "AddWithdraw"://申请提现
                    result = AddWithdraw();
                    break;
                case "GetWithdrawList":
                    result = GetWithdrawList();
                    break;
                case "AddBankCard":
                    result = AddBankCard();
                    break;
                case "GetBankCC":
                    result = GetBankCC();
                    break;
                case "GetBankDC":
                    result = GetBankDC();
                    break;
                case "GetBankCardAll":
                    result = GetBankCardAll();
                    break;
                case "GetBank":
                    result = GetBank();
                    break;
                case "GetBankNames":
                    result = GetBankNames();
                    break;
                case "GetBillList":
                    result = GetBillList();
                    break;
                case "GetRechargeList":
                    result = GetRechargeList();
                    break;
                case "GetMessageList":
                    result = GetMessageList();
                    break;
                case "GetHomeNoticeList":
                    result = GetHomeNoticeList();
                    break;
                case "GetHomeNewsList":
                    result = GetHomeNewsList();
                    break;
                case "GetNoticeList":
                    result = GetNoticeList();
                    break;
                case "GetNotice":
                    result = GetNotice();
                    break;
                case "GetAsset":
                    result = GetAsset();
                    break;
                case "GetNewsList":
                    result = GetNewsList();
                    break;
                case "GetFAQList":
                    result = GetFAQList();
                    break;
                case "GetRegisterAuthCode":
                    result = GetRegisterAuthCode();
                    break;
                case "Register":
                    result = Register();
                    break;
                case "SetNewPassword":
                    result = SetNewPassword();
                    break;
                case "GetHomeBanner":
                    result = GetHomeBanner();
                    break;
                case "GetsByTradeFeeAward":
                    result = GetsByTradeFeeAward();
                    break;
                case "GetTradeFeeAwardStat":
                    result = GetTradeFeeAwardStat();
                    break;
                case "AddRecharge":
                    result = AddRecharge();
                    break;
                case "SignalRLogin":
                    result = SignalRLogin();
                    break;
                case "SetAllRead":
                    SetAllRead();
                    break;
                case "GetUser":
                    result = GetUser();
                    break;
                case "GetCash":
                    result = GetCash();
                    break;
                case "GetRepaymentPlanSummary":
                    result = GetRepaymentPlanSummary();
                    break;
                case "GetRepaymentPlans":
                    result = GetRepaymentPlans();
                    break;
                case "GetRepaymentPlanPreview":
                    result = GetRepaymentPlanPreview();
                    break;
                case "AddRepaymentPlan":
                    result = AddRepaymentPlan();
                    break;
                case "Pay":
                    result = Pay();
                    break;
                case "GetRepaymentPlanItems":
                    result = GetRepaymentPlanItems();
                    break;
            }
            context.Response.Write(result);
            context.Response.End();
        }

        private string GetUser()
        {
            return bllMemberInfo.GetAppUserData(memberAccount, null);
        }

        /// <summary>
        /// 获得还款计划明细
        /// </summary>
        /// <returns></returns>
        private string GetRepaymentPlanItems()
        {
            var planID = WebHelper.Post<int>("ID");
            var items = bllRepaymentPlanItem.Gets(planID);
            List<PlanRepayment> list = new List<PlanRepayment>();
            PlanRepayment plan;

            foreach (var item in items.Where(m=>m.ParentID==0))
            {
                plan = new PlanRepayment { Amount = item.Amount, ActionTime = item.Date, Status = (RepaymentPlanStatus)item.Status };
                plan.Pays = new List<PlanPay>();

                foreach (var item1 in items.Where(m => m.ParentID == item.ItemID))
                {
                    plan.Pays.Add(new PlanPay { Amount=item1.Amount, ActionTime=item1.Date, Status = (RepaymentPlanStatus)item1.Status });
                }

                list.Add(plan);
            }

            return Core.GetJsonByListHaveTime(list);
        }

        /// <summary>
        /// 支付
        /// </summary>
        /// <returns></returns>
        private string Pay()
        {
            var id = WebHelper.Post<string>("ID");
            var amount = WebHelper.Post<decimal>("Amount");
            var paytype = WebHelper.Post<int>("PayType");
            var tradetype = (PayTradeType)WebHelper.Post<int>("TradeType");

            return new PPayHelper().Pay(memberAccount, id, amount, paytype, 0, tradetype);
        }

        /// <summary>
        /// 获得用户银行卡还款信息汇总
        /// </summary>
        /// <returns></returns>
        private string GetRepaymentPlans()
        {
            var cardID = WebHelper.Post<int>("CardID");
            return Core.GetJsonByList(bllRepaymentPlan.GetsByMember(memberAccount, cardID));
        }

        /// <summary>
        /// 获得用户银行卡还款统计
        /// </summary>
        /// <returns></returns>
        private string GetRepaymentPlanSummary()
        {
            var cardID = WebHelper.Post<int>("CardID");
            return Core.GetJsonByObject(bllRepaymentPlan.GetSummary(memberAccount, cardID));
        }

        /// <summary>
        /// 提交计划
        /// </summary>
        /// <returns></returns>
        private string AddRepaymentPlan()
        {
            var id = WebHelper.Post<int>("ID");
            var plan = bllRepaymentPlan.Get(id);

            if (plan == null)
            {
                return Core.AjaxResult(false, "提交失败，计划不存在");
            }

            if (bllRepaymentPlan.UpdateStatus(id, RepaymentPlanStatus.Unpay))
            {
                return Core.AjaxResult(true, "", new { Amount=plan.RepaymentAmount+plan.Fee });
            }
            else
            {
                return Core.AjaxResult(false, "提交计划失败，请重试");
            }
        }

        /// <summary>
        /// 获得还款预览
        /// </summary>
        /// <returns></returns>
        private string GetRepaymentPlanPreview()
        {
            var ccID = WebHelper.Post<int>("CCID");
            var total = WebHelper.Post<decimal>("BillAmount");
            var amount = WebHelper.Post<decimal>("Amount");

            if (total < BLL.ConfigParameters.Repayment.MaxBillAmount)
            {
                return Core.AjaxResult(false, string.Format("账单金额{0}起", BLL.ConfigParameters.Repayment.MaxBillAmount));
            }
            if (amount / total < BLL.ConfigParameters.Repayment.CashDepositRate || amount < BLL.ConfigParameters.Repayment.MinCashDeposit)
            {
                return Core.AjaxResult(false, string.Format("保证金{0}%起不低于{1}元", BLL.ConfigParameters.Repayment.CashDepositRate*100, BLL.ConfigParameters.Repayment.MinCashDeposit));
            }
            var cardCC = bllBankCard.Get(ccID);
            if (cardCC == null)
            {
                return Core.AjaxResult(false, "信用卡错误");
            }

            var fee = total * BLL.ConfigParameters.Repayment.FeeRate;

            List<PlanRepayment> list = new List<PlanRepayment>();
            int repayDay = cardCC.RepaymentDate;
            decimal split = BLL.ConfigParameters.Repayment.AmountSplit;
            decimal balance = total;
            decimal temp = 0, repay = 0, repayBalance = 0;
            var r = new Random();
            var i = 0;

            #region 构造还款
            do
            {
                var rv = (decimal)(r.Next(1, 20));
                temp = amount; //(80 + rv) / 100 * amount;

                if (amount > balance)
                {
                    temp = balance;
                }

                balance -= temp;
                repay = balance == 0 ? temp - repayBalance : amount - repayBalance;

                repayBalance = amount - temp;
                list.Add(new PlanRepayment { ActionTime = DateTime.Now, Amount = repay, Pay = new PlanPay { ActionTime = DateTime.Now, Amount = temp } });

                if (balance == 0)
                {
                    break;
                }

                i++;
            }
            while (i < 20);
            #endregion

            #region 构造时间
            DateTime todayLastTime = DateTime.Today.AddHours(BLL.ConfigParameters.Repayment.TodayLastTime);            
            int days = repayDay - DateTime.Today.Day + 1;
            int daysCount = 0;
            i = 0;

            //如果还款日小于当前日，则只能还下个月的账单
            if (repayDay < DateTime.Today.Day)
            {
                var repayDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, repayDay).AddMonths(1);
                days = (repayDate - DateTime.Today).Days;
            }
            //如果当前时间大于当日最后还款时间，则还款天数需减掉一日
            if (DateTime.Now > todayLastTime)
            {
                days -= 1;
            }

            daysCount = (int)Math.Ceiling((decimal)list.Count / (decimal)days);
            //如果还款天数大于还款笔数，则说明还款时间充足，因此每日还款一笔即可
            if (days > list.Count)
            {
                days = list.Count;
                daysCount = 1;
            }

            if (daysCount > 2)
            {
                return Core.AjaxResult(false, "离还款日太近，请提高保证金");
            }

            for (var j = 1; j <= days; j++)
            {
                for (var n = 1; n <= daysCount; n++)
                {
                    list[i].ActionTime = DateTime.Today.AddDays(DateTime.Now < todayLastTime ? j - 1 : j).AddHours(r.Next(BLL.ConfigParameters.Repayment.DaysBeginTime + 9 / daysCount * (n - 1), BLL.ConfigParameters.Repayment.DaysBeginTime + 9 / daysCount * n)).AddMinutes(r.Next(1, 59)).AddSeconds(r.Next(1, 59));

                    i++;

                    if (i >= list.Count)
                    {
                        j = days + 1;
                        break;
                    }
                }
            }
            #endregion

            #region 构造消费
            temp = 0;
            balance = 0;
            DateTime payActionTime;
            foreach (var item in list)
            {

                if (item.Pays == null)
                {
                    item.Pays = new List<PlanPay>();
                }


                if (item.Pay.Amount > split)
                {
                    balance = item.Pay.Amount;
                    while (true)
                    {
                        var rv = (decimal)(r.Next(1, 30));
                        temp = (20 + rv) / 100 * item.Pay.Amount;

                        if (temp > balance)
                        {
                            temp = balance;
                        }

                        payActionTime = item.ActionTime.AddHours(r.Next(0, BLL.ConfigParameters.Repayment.DaysEndTime - item.ActionTime.Hour)).AddMinutes(r.Next(1, 60)).AddSeconds(r.Next(1, 60));
                        item.Pays.Add(new PlanPay { ActionTime = payActionTime, Amount = temp });

                        balance -= temp;

                        if (balance == 0)
                        {
                            break;
                        }
                    }

                    item.Pays = item.Pays.OrderBy(m => m.ActionTime).ToList();
                }
                else
                {
                    payActionTime = item.ActionTime.AddHours(r.Next(0, BLL.ConfigParameters.Repayment.DaysEndTime - item.ActionTime.Hour)).AddMinutes(r.Next(1, 60)).AddSeconds(r.Next(1, 60));
                    item.Pays.Add(new PlanPay { ActionTime = payActionTime, Amount = item.Pay.Amount });
                }
            }
            #endregion

            if (new CR_RepaymentPlanBLL().Save(memberAccount, ccID, total, amount, fee, list))
            {
                var plan = bllRepaymentPlan.Get(memberAccount, ccID);
                return Core.AjaxResult(true, "", new { Plan=plan, Items=list });
            }
            else
            {
                return Core.AjaxResult(false, "预览计划发生错误");
            }
        }
        
        /// <summary>
        /// 取现
        /// </summary>
        /// <returns></returns>
        private string GetCash()
        {
            var bllBank = new Sys_BankBLL();
            decimal amount = WebHelper.Post<decimal>("Amount");
            int ccID = WebHelper.Post<int>("CCID");//信用卡ID
            int dcID = WebHelper.Post<int>("DCID");//储蓄卡ID

            if (amount < BLL.ConfigParameters.GetCash.GetCashMinAmount)
            {
                return Core.AjaxResult(false, "最小取现金额" + BLL.ConfigParameters.GetCash.GetCashMinAmount.ToString("n0") + "元起");
            }
            if (amount > BLL.ConfigParameters.GetCash.GetCashMaxAmount)
            {
                return Core.AjaxResult(false, "超过最大取现金额" + BLL.ConfigParameters.GetCash.GetCashMaxAmount.ToString("n0") + "元");
            }

            //支付手续费+取现手续费
            decimal fee = amount * BLL.ConfigParameters.Recharge.RechargeFee + BLL.ConfigParameters.GetCash.GetCashFee;
            decimal getAmount = amount - fee;

            var cardCC = bllBankCard.Get(ccID);
            var cardDC = bllBankCard.Get(dcID);

            if (cardCC == null || cardCC.MemberAccount != memberAccount)
            {
                return Core.AjaxResult(false, "请选择取现信用卡");
            }
            if (cardDC == null || cardDC.MemberAccount != memberAccount)
            {
                return Core.AjaxResult(false, "请选择收款储蓄卡");
            }

            #region 提现表
            var withdraw = new Member_Withdraw();
            withdraw.MoneyType = "RMB";
            withdraw.MemberAccount = memberAccount;
            withdraw.WithdrawID = bllWithdraw.GenerateID().ToString();
            withdraw.PayAmount = amount;
            withdraw.WithdrawAmount = getAmount;
            withdraw.WithdrawFee = fee;

            //付款信用卡
            withdraw.PayBankAccountName = cardCC.Name;
            withdraw.PayBankAccountNo = cardCC.CardNo;
            withdraw.PayBankMobileNo = cardCC.BankMobile;
            withdraw.PayIDNo = cardCC.IDNo;
            withdraw.PayBankCode = cardCC.BankCode;
            withdraw.PayBankName = cardCC.BankName;

            //收款储蓄卡
            withdraw.BankCode = cardDC.BankCode;
            withdraw.BankName = cardDC.BankName;
            withdraw.BankAccountName = cardDC.Name;
            withdraw.BankAccountNo = cardDC.CardNo;

            withdraw.Status = WithdrawStatus.Pending;

            if (!bllWithdraw.Add(withdraw))
            {
                return Core.AjaxResult(false, "系统异常，请稍候");
            }
            #endregion
            
            return new PPayHelper().Pay(memberAccount, withdraw.WithdrawID, amount, cardCC.ID, cardDC.ID, PayTradeType.Withdraw);

            //return Core.AjaxResult(true, "取现成功", withdraw);
        }

        private void SetAllRead()
        {
            Task.Run(() => {
                new CMS_MessageBLL().SetAllRead(memberAccount);
            });
        }

        private string SignalRLogin()
        {
            return Core.SignalRMinLogin(HttpContext.Current);
        }

        /// <summary>
        /// 新增充值
        /// </summary>
        /// <returns></returns>
        private string AddRecharge()
        {
            Member_RechargeBLL bll = new Member_RechargeBLL();
            decimal amount = WebHelper.Post<decimal>("Amount");

            Member_Recharge model = new Member_Recharge();

            model.RechargeID = bll.GenerateID();
            model.MemberAccount = memberAccount;

            model.FromBankName = string.Empty;
            model.FromBankAccountNo = string.Empty;
            model.FromBankAccountName = string.Empty;
            model.FromAmount = amount;

            model.ToBankName = string.Empty;
            model.ToBankAccountNo = string.Empty;
            model.ToBankAccountName = string.Empty;
            model.ToAmount = 0;

            model.MoneyType = "RMB";
            model.Accessory = string.Empty;
            model.Memo = string.Empty; 
            model.TransferTime = DateTime.Now;
            model.Status = RechargeStatus.Waiting;
            model.CreateTime = DateTime.Now;
            model.ModifyTime = DateTime.Now;

            if (bll.Add(model))
            {
                return Core.AjaxResult(true, "", model);
            }

            return Utility.AjaxResult(false, AjaxResultType.Save);
        }

        private string AddQRRecharge()
        {
            Member_RechargeBLL bll = new Member_RechargeBLL();
            decimal amount = WebHelper.Post<decimal>("Amount");

            Member_Recharge model = new Member_Recharge();

            var payQR = GetPayQR(memberAccount, amount);

            model.RechargeID = bll.GenerateID();
            model.MemberAccount = memberAccount;

            model.FromBankName = "微信";
            model.FromBankAccountNo = string.Empty;
            model.FromBankAccountName = string.Empty;
            model.FromAmount = amount;

            model.ToBankName = string.Empty;
            model.ToBankAccountNo = string.Empty;
            model.ToBankAccountName = string.Empty;
            model.ToAmount = 0;

            model.MoneyType = "RMB";
            model.Accessory = string.Empty;
            model.Memo = string.Empty;
            model.TransferTime = DateTime.Now;
            model.Status = RechargeStatus.Waiting;
            model.CreateTime = DateTime.Now;
            model.ModifyTime = DateTime.Now;
            model.QRCodeID = payQR.QRCodeID;

            if (bll.Add(model))
            {
                return Utility.AjaxResult(true, "新建充值成功", payQR);
            }
            else
            {
                return Utility.AjaxResult(false, AjaxResultType.Save);
            }
        }

        private dynamic GetPayQR(string memberAccount, decimal amount)
        {
            int payType = 1;
            var row = (new Pay_QRCodeBLL().GetPayQR(memberAccount, payType, amount));
            var imgUrl = row["Img"].ToString();
            return new {
                QRCodeID = (int)row["ID"],
                Img = WebHelper.FullHostHttp + imgUrl,
            };
        }

        private string GetTradeFeeAwardStat()
        {
            var memberAccount = WebHelper.Post("MemberAccount");
            return Core.GetJsonByObject(new Member_AssetHistoryBLL().GetTradeFeeAwardStat(memberAccount));
        }

        private string GetsByTradeFeeAward()
        {
            return Core.GetJsonByList(new Member_AssetHistoryBLL().GetsByTradeFeeAward());
        }

        private string SetNewPassword()
        {
            return bllMemberInfo.SetNewPassword();
        }

        private string Register()
        {
            return bllMemberInfo.Register();
        }

        private string GetRegisterAuthCode()
        {
            return bllMemberInfo.GetRegisterAuthCode();
        }

        private string GetAsset()
        {
            return Core.GetJsonByObject(new Member_AccountBLL().Get(memberAccount));
        }

        private string GetNotice()
        {
            Int64 NoticeID = WebHelper.Post<Int64>("NoticeID");

            var item = new CMS_ArticleBLL().Get(NoticeID);

            item.Content = item.Content.Replace('[', '<').Replace(']', '>').Replace("<file src=\"/UpLoad/", string.Format("<file src=\"{0}/UpLoad/", WebHelper.FullHostHttp));

            return Core.GetJsonByObjectHaveTime(item);
        }

        private string GetHomeBanner()
        {
            return GetArticleList(23);
        }

        private string GetNoticeList()
        {
            return GetArticleList(18);
        }

        private string GetNewsList()
        {
            return GetArticleList(22);
        }

        private string GetFAQList()
        {
            return GetArticleList(19);
        }

        private string GetArticleList(int menuID)
        {
            var where = " IsPublish=1 and MenuID=" + menuID.ToString();
            var lastID = WebHelper.Post<int>("LastID");
            var firstID = WebHelper.Post<int>("FirstID");
            if (firstID > 0)
            {
                where += " and ID > @FirstID";
            }
            else if (lastID > 0)
            {
                where += " and ID < @LastID";
            }
            DataTable dt = new CMS_ArticleBLL().Gets(20, where, "ID,Title,Content,Cover,PublishTime",
                new SqlParameter[] {
                    new SqlParameter("@LastID", lastID),
                    new SqlParameter("@FirstID", firstID)
                });

            foreach (DataRow row in dt.Rows)
            {
                row["Content"] = CommonHelper.GetNewsIntro(row["Content"].ToString().Replace("[", "<").Replace("]", ">"));
            }

            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetHomeNoticeList()
        {
            DataTable dt = new CMS_ArticleBLL().GetsTop();

            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetHomeNewsList()
        {
            var where = " IsPublish=1 and MenuID=22 ";
            DataTable dt = new CMS_ArticleBLL().Gets(20, where, "ID,Title,PublishTime");

            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetMessageList()
        {
            int total;
            var where = " MemberAccount = @MemberAccount ";
            var lastID = WebHelper.Post<int>("LastID");
            var firstID = WebHelper.Post<int>("FirstID");
            if (firstID > 0)
            {
                where += " and MessageID > @FirstID";
            }
            else if (lastID > 0)
            {
                where += " and MessageID < @LastID";
            }
            DataTable dt = new CMS_MessageBLL().Gets(where, 0, 20, out total,
                new SqlParameter[] {
                    new SqlParameter("@MemberAccount", WebHelper.Post("MemberAccount")),
                    new SqlParameter("@LastID", lastID),
                    new SqlParameter("@FirstID", firstID)
                });
            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetRechargeList()
        {
            int total;
            DataTable dt = new Member_RechargeBLL().Gets(" r.MemberAccount = @MemberAccount ", 0, 100, out total, new SqlParameter[] { new SqlParameter("@MemberAccount", WebHelper.Post("MemberAccount")) });

            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetBillList2()
        {
            int total;
            var where = " MemberAccount = @MemberAccount and ChangeType in (304) ";
            var lastID = WebHelper.Post<int>("LastID");
            var firstID = WebHelper.Post<int>("FirstID");
            if (firstID > 0)
            {
                where += " and a.TradeID > @FirstID";
            }
            else if (lastID > 0)
            {
                where += " and a.TradeID < @LastID";
            }
            DataTable dt = new Member_AssetHistoryBLL().Gets(where, 0, 20, out total,
                new SqlParameter[] {
                    new SqlParameter("@MemberAccount", WebHelper.Post("MemberAccount")),
                    new SqlParameter("@LastID", lastID),
                    new SqlParameter("@FirstID", firstID)
                });
            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetBillList()
        {
            var MoneyType = WebHelper.Post<string>("MoneyType");
            int total;
            var where = " MemberAccount = @MemberAccount ";

            if (MoneyType == "Repay")
            {
                where += " and MoneyType = '还款'";
            }
            else if (MoneyType == "Withdraw")
            {
                where += " and MoneyType = '取现'";
            }
            else if (MoneyType == "Recharge")
            {
                where += " and MoneyType = '充值'";
            }
            else if (MoneyType == "Dividend")
            {
                where += " and (MoneyType = '新人推荐' or MoneyType ='利息分红') ";
            }

            DataTable dt = new Member_AssetHistoryBLL().BillGets(where, 0, 20, out total,
                new SqlParameter[] {
                    new SqlParameter("@MemberAccount", WebHelper.Post("MemberAccount"))
                });
            return Core.GetJsonByListHaveTime(dt);
        }

        private string GetBankNames()
        {
            var nodes = Youz.CreditRepay.BLL.ConfigParameters.BankNameList.Split(',');
            StringBuilder sb = new StringBuilder();
            string[] value;

            sb.Append("[");
            foreach (var node in nodes)
            {
                if (string.IsNullOrEmpty(node)) continue;
                value = node.Split('|');
                if (value.Length == 2)
                {
                    sb.AppendFormat("{{\"value\":\"{0}\", \"text\":\"{1}\"}},", value[0], value[1]);
                }
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]");

            return sb.ToString();
        }

        /// <summary>
        /// 支持的银行
        /// </summary>
        /// <returns></returns>
        private string GetBank()
        {
            return Core.GetJsonByObject(new Sys_BankBLL().Gets());
        }

        /// <summary>
        /// 信用卡
        /// </summary>
        /// <returns></returns>
        private string GetBankCC()
        {
            return GetBankCard(BankCardType.CreditCard);
        }

        /// <summary>
        /// 储蓄卡
        /// </summary>
        /// <returns></returns>
        private string GetBankDC()
        {
            return GetBankCard(BankCardType.DepositCard);
        }

        /// <summary>
        /// 获得所有银行卡
        /// </summary>
        /// <returns></returns>
        private string GetBankCardAll()
        {
            return GetBankCard(BankCardType.All);
        }

        private string GetBankCard(BankCardType type)
        {
            var ds = bllBankCard.GetsByMember(memberAccount, type);

            return Core.GetJsonByList(ds);
        }

        private string AddBankCard()
        {
            CR_BankCard model = new CR_BankCard();
            var mobile = WebHelper.Post<String>("BankMobile");
            var authCode = WebHelper.Post("AuthCode");

            if (string.IsNullOrWhiteSpace(mobile) || string.IsNullOrWhiteSpace(authCode))
            {
                return Utility.AjaxResult(false, "请输入");
            }

            string phonecode = SessionHelper.Get("phonecode") as string;
            if ((mobile + authCode) != phonecode)
                return Utility.AjaxResult(false, "验证码不正确或已过期");

            model.Name = WebHelper.Post<String>("Name");
            model.Password = WebHelper.Post<String>("Password");
            model.Type = WebHelper.Post<int>("Type");
            model.IDNo = WebHelper.Post<String>("IDNo");
            model.CardNo = WebHelper.Post<String>("CardNo");
            model.CVV2 = WebHelper.Post<String>("CVV2");
            model.ExpiryDate = WebHelper.Post<String>("ExpiryDate");

            model.BankCode = WebHelper.Post<String>("BankCode");
            var bank = new Sys_BankBLL().GetsByCode(model.BankCode);
            model.BankName = bank.Name;
            model.BankAbbr = bank.NameAbbr;

            model.BillingDate = WebHelper.Post<Int32>("BillingDate");
            model.RepaymentDate = WebHelper.Post<Int32>("RepaymentDate");
            model.BillingEmail = WebHelper.Post<String>("BillingEmail");
            model.BankMobile = mobile;
            model.RepaymentAmount = 0;
            model.RepaymentedAmount = 0;
            model.DepositAmount = 0;
            model.IsDefault = false;
            model.MemberAccount = memberAccount;

            if (string.IsNullOrWhiteSpace(model.Name) || string.IsNullOrWhiteSpace(model.IDNo) || string.IsNullOrWhiteSpace(model.CardNo) || string.IsNullOrWhiteSpace(model.BankCode))
            {
                return Utility.AjaxResult(false, "请输入");
            }
            if (model.Type == 0)
            {
                if (string.IsNullOrWhiteSpace(model.ExpiryDate) || string.IsNullOrWhiteSpace(model.CVV2) || model.BillingDate == 0 || model.RepaymentDate == 0)
                {
                    return Utility.AjaxResult(false, "请输入");
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(model.Password))
                {
                    return Utility.AjaxResult(false, "请输入");
                }
            }  

            if (bllBankCard.Exists(memberAccount, model.BankCode, model.Name, model.CardNo))
                return Utility.AjaxResult(false, "银行卡已存在");

            if (bllBankCard.Add(model))
            {
                return Utility.AjaxResult(true, AjaxResultType.Save);
            }
            else
            {
                return Utility.AjaxResult(false, AjaxResultType.Save);
            }
        }

        private string GetWithdrawList()
        {
            var bllWithdraw = new Member_WithdrawBLL();
            int total;
            DataTable dt = bllWithdraw.Gets(" a.MemberAccount = @MemberAccount ", 0, 100, out total, new SqlParameter[] { new SqlParameter("@MemberAccount", memberAccount) });

            foreach (DataRow row in dt.Rows)
            {
                bllWithdraw.GetPayEaseStatusAsyn(row["WithdrawID"].ToString());
            }

            return Core.GetJsonByListHaveTime(dt);
        }

        /// <summary>
        /// 申请提现
        /// </summary>
        /// <returns></returns>
        private string AddWithdraw()
        {
            var cardID = WebHelper.Post<int>("CardID");
            var amount = WebHelper.Post<decimal>("WithdrawAmount");

            return new Member_WithdrawBLL().BalanceWithdraw(memberAccount, cardID, amount);
        }
        
        private string AuthenticationMember()
        {
            //是否开启身份认证
            if (!Youz.CreditRepay.BLL.ConfigParameters.EnabledMemberCerified)
            {
                return Core.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Certified, "CheckEnabledMemberCerified", "认证失败，身份认证未开启"));
            }

            Member_Certified model = new Member_Certified();
            model.MemberAccount = memberAccount;

            Member_CertifiedBLL bll = new Member_CertifiedBLL();
            StringBuilder str = new StringBuilder();

            DataTable dt = bll.Gets(" memberaccount='" + model.MemberAccount + "' and( status=0 or status=2) ").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                return Core.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Certified, "CheckExistsMemberCerified", "认证失败，您已申请过认证"));
            }

            string CredentialsNum = WebHelper.Post("IDNo").Trim();
            DataTable dt1 = bll.Gets(str.AppendFormat("CredentialsNum='{0}' and (status=0 or status=2) ", CredentialsNum).ToString()).Tables[0];
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                return Core.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Certified, "CheckExistsID", "认证失败，证件号已认证"));
            }

            model.CertifiedID = Guid.NewGuid();
            model.CreateTime = DateTime.Now;
            model.Name = WebHelper.Post("Name").Trim();
            model.CredentialsNum = CredentialsNum;
            model.CredentialsType = "身份证";
            model.Memo = string.Empty;
            model.CardNum = string.Empty;
            model.Address = string.Empty;
            model.Phone = string.Empty;
            model.Status = AuditStatus.Waiting;
            model.Img = CommonHelper.UpLoadBase64Img(WebHelper.Post("img1")) + "||" + CommonHelper.UpLoadBase64Img(WebHelper.Post("img2"));

            if (bll.Add(model))
            {

                return Core.AjaxResult(true);
            }
            else
            {
                return Core.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Certified, "AddError", "认证失败，请稍后再试"));
            }
        }

        private string ChangeLoginPassword()
        {
            var account = WebHelper.Post("MemberAccount");

            if (string.IsNullOrEmpty(account))
            {
                return Utility.AjaxResult(false, "错误，请确定您的输入");
            }

            Member_Info model = new Member_Info();
            model = bllMemberInfo.Get(account);

            if (model == null)
            {
                return Utility.AjaxResult(false, "错误，请确定您的输入");
            }
            if (model.LoginPwd != CommonHelper.GetSHA512(WebHelper.Post<String>("Password")))
            {
                return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Info, "ChangePassword_Error_Current", "登錄密碼錯誤，請重新輸入。"));
            }
            if (WebHelper.Post<String>("NewPassword") != WebHelper.Post<String>("ConfirmNewPassword"))
            {
                return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Info, "ChangePassword_Error_NewLoginPwd", "新登錄密碼输入不一致，請重新輸入。"));
            }

            var password = CommonHelper.GetSHA512(WebHelper.Post<String>("NewPassword"));

            bllMemberInfo.ChangeLoginPassword(account, password);

            return Utility.AjaxResult(true, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Info, "ChangePassword_Success", "登录密碼修改成功。"));
        }

        private string ChangePayPassword()
        {
            var account = WebHelper.Post("MemberAccount");

            if (string.IsNullOrEmpty(account))
            {
                return Utility.AjaxResult(false, "错误，请确定您的输入");
            }

            Member_Info model = new Member_Info();
            model = bllMemberInfo.Get(account);

            if (model == null)
            {
                return Utility.AjaxResult(false, "错误，请确定您的输入");
            }
            if (model.CapitalPwd != CommonHelper.GetSHA512(WebHelper.Post<String>("Password")))
            {
                return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Info, "ChangePassword_Error_OldCapitalPwd", "交易密碼錯誤，請重新輸入。"));
            }
            if (WebHelper.Post<String>("NewPassword") != WebHelper.Post<String>("ConfirmNewPassword"))
            {
                return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Info, "ChangePassword_Error_NewCapitalPwd", "新交易密碼输入不一致，請重新輸入。"));
            }

            var password = CommonHelper.GetSHA512(WebHelper.Post<String>("NewPassword"));

            bllMemberInfo.ChangePayPassword(account, password);

            return Utility.AjaxResult(true, Lang_LanguageBLL.LanguageByManage(LanguageModule.Member_Info, "ChangePassword_CapitalPwd_Success", "交易密碼修改成功。"));
            
        }

        private string SetNickname()
        {
            bllMemberInfo.SetNickname(WebHelper.Post("MemberAccount"), WebHelper.Post("Nickname"));
            return Core.AjaxResult(true);
        }

        /// <summary>
        /// 获得最新版本号
        /// </summary>
        /// <returns></returns>
        private string GetVersion()
        {
            var version = new Sys_VersionBLL().GetLatest();
            if (version == null)
            {
                version = new Sys_Version();
                version.PackageType = AppPackageType.Package;
                version.VersionNo = "0.0.0";
                version.IsForceUpdate = 0;
                version.Package = "";
            }
            var updates = new
            {
                type = (int)version.PackageType,
                version = version.VersionNo,
                title = "版本更新",
                note = "检测到有新版本，确定后将进入下载页面",
                isForce = version.IsForceUpdate,
                url = WebHelper.FullHostHttp + version.Package
            };
            return Core.GetJsonByObject(updates);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        private string Login()
        {
            string UserName = WebHelper.Post("account").Trim();
            string Password = WebHelper.Post("password").Trim();
            string authcode = WebHelper.Post("authcode").Trim();
            string AppID = WebHelper.Post("AppID");

            if (string.IsNullOrEmpty(UserName)) return Core.AjaxResult(false, "请输入手机号");

            Member_Info model = new Member_InfoBLL().Get(UserName);

            if (!string.IsNullOrEmpty(Password))
            {
                if (string.IsNullOrEmpty(Password)) return Core.AjaxResult(false, "请输入密码");
                if (model == null || model.LoginPwd != CommonHelper.GetSHA512(Password))
                {
                    return Core.AjaxResult(false, "帐号或密码错误");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(authcode)) return Core.AjaxResult(false, "请输入短信验证码");

                string phonecode = SessionHelper.Get("phonecode") as string;
                if ((UserName + authcode) != phonecode)
                    return Utility.AjaxResult(false, "验证码不正确或已过期");
                if (model == null)
                {
                    return Core.AjaxResult(false, "手机号未注册");
                }
            }
            
            if (model.Status == MemberStatus.LockedLogin)
            {
                Core.WriteLoginLog(false, UserName, (int)Core.CurrentSiteType, "登录失败,您的帐号被禁用!");
                return Core.AjaxResult(false, "登录失败,您的帐号被禁用!");
            }

            return bllMemberInfo.Login(UserName, AppID, model);
        }

        /// <summary>
        /// APP登出
        /// </summary>
        private string Logout()
        {
            bllMemberInfo.LogoutApp(WebHelper.Post("account"));
            return Core.AjaxResult(true);
        }
               
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}